{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convolutional Neural Networks (LeNet)\n",
    "\n",
    ":label:`sec_lenet`\n",
    "\n",
    "\n",
    "We now have all the ingredients required to assemble\n",
    "a fully-functional convolutional neural network.\n",
    "In our first encounter with image data,\n",
    "we applied a multilayer perceptron (:numref:`sec_mlp_scratch`)\n",
    "to pictures of clothing in the Fashion-MNIST dataset.\n",
    "To make this data amenable to multilayer perceptrons,\n",
    "we first flattened each image from a $28\\times28$ matrix\n",
    "into a fixed-length $784$-dimensional vector,\n",
    "and thereafter processed them with fully-connected layers.\n",
    "Now that we have a handle on convolutional layers,\n",
    "we can retain the spatial structure in our images.\n",
    "As an additional benefit of replacing dense layers with convolutional layers, \n",
    "we will enjoy more parsimonious models (requiring far fewer parameters).\n",
    "\n",
    "In this section, we will introduce LeNet,\n",
    "among the first published convolutional neural networks\n",
    "to capture wide attention for its performance on computer vision tasks.\n",
    "The model was introduced (and named for) Yann Lecun,\n",
    "then a researcher at AT&T Bell Labs,\n",
    "for the purpose of recognizing handwritten digits in images \n",
    "[LeNet5](http://yann.lecun.com/exdb/lenet/).\n",
    "This work represented the culmination\n",
    "of a decade of research developing the technology.\n",
    "In 1989, LeCun published the first study to successfully\n",
    "train convolutional neural networks via backpropagation. \n",
    "\n",
    "\n",
    "At the time LeNet achieved outstanding results \n",
    "matching the performance of Support Vector Machines (SVMs),\n",
    "then a dominant approach in supervised learning.\n",
    "LeNet was eventually adapted to recognize digits \n",
    "for processing deposits in ATM machines.\n",
    "To this day, some ATMs still run the code \n",
    "that Yann and his colleague Leon Bottou wrote in the 1990s!\n",
    "\n",
    "\n",
    "## LeNet\n",
    "\n",
    "At a high level, LeNet consists of three parts:\n",
    "(i) a convolutional encoder consisting of two convolutional layers; and\n",
    "(ii) a dense block consisting of three fully-connected layers;\n",
    "The architecture is summarized in :numref:`img_lenet`.\n",
    "\n",
    "![Data flow in LeNet 5. The input is a handwritten digit, the output a probability over 10 possible outcomes.](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/lenet.svg)\n",
    "\n",
    ":label:`img_lenet`\n",
    "\n",
    "\n",
    "The basic units in each convolutional block \n",
    "are a convolutional layer, a sigmoid activation function,\n",
    "and a subsequent average pooling operation.\n",
    "Note that while ReLUs and max-pooling work better,\n",
    "these discoveries had not yet been made in the 90s. \n",
    "Each convolutional layer uses a $5\\times 5$ kernel\n",
    "and a sigmoid activation function.\n",
    "These layers map spatially arranged inputs\n",
    "to a number of 2D feature maps, typically \n",
    "increasing the number of channels.\n",
    "The first convolutional layer has 6 output channels,\n",
    "while th second has 16.\n",
    "Each $2\\times2$ pooling operation (stride 2) \n",
    "reduces dimensionality by a factor of $4$ via spatial downsampling.\n",
    "The convolutional block emits an output with size given by\n",
    "(batch size, channel, height, width).\n",
    "\n",
    "In order to pass output from the convolutional block\n",
    "to the fully-connected block, \n",
    "we must flatten each example in the minibatch.\n",
    "In other words, we take this 4D input and transform it\n",
    "into the 2D input expected by fully-connected layers:\n",
    "as a reminder, the 2D representation that we desire\n",
    "has uses the first dimension to index examples in the minibatch\n",
    "and the second to give the flat vector representation of each example.\n",
    "LeNet's fully-connected layer block has three fully-connected layers,\n",
    "with 120, 84, and 10 outputs, respectively.\n",
    "Because we are still performing classification,\n",
    "the 10-dimensional output layer corresponds\n",
    "to the number of possible output classes.\n",
    "\n",
    "While getting to the point where you truly understand\n",
    "what is going on inside LeNet may have taken a bit of work,\n",
    "hopefully the following code snippet will convince you\n",
    "that implementing such models with modern deep learning libraries \n",
    "is remarkably simple. \n",
    "We need only to instantiate a `Sequential` Block \n",
    "and chain together the appropriate layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.basicdataset.cv.classification.*;\n",
    "import ai.djl.metric.*;\n",
    "import org.apache.commons.lang3.ArrayUtils;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Engine.getInstance().setRandomSeed(1111);\n",
    "\n",
    "NDManager manager = NDManager.newBaseManager();\n",
    "\n",
    "SequentialBlock block = new SequentialBlock();\n",
    "\n",
    "block\n",
    "    .add(Conv2d.builder()\n",
    "                .setKernelShape(new Shape(5, 5))\n",
    "                .optPadding(new Shape(2, 2))\n",
    "                .optBias(false)\n",
    "                .setFilters(6)\n",
    "                .build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Pool.avgPool2dBlock(new Shape(5, 5), new Shape(2, 2), new Shape(2, 2)))\n",
    "    .add(Conv2d.builder()\n",
    "                .setKernelShape(new Shape(5, 5))\n",
    "                .setFilters(16).build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Pool.avgPool2dBlock(new Shape(5, 5), new Shape(2, 2), new Shape(2, 2)))\n",
    "    // Blocks.batchFlattenBlock() will transform the input of the shape (batch size, channel,\n",
    "    // height, width) into the input of the shape (batch size,\n",
    "    // channel * height * width)\n",
    "    .add(Blocks.batchFlattenBlock())\n",
    "    .add(Linear\n",
    "                .builder()\n",
    "                .setUnits(120)\n",
    "                .build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Linear\n",
    "                .builder()\n",
    "                .setUnits(84)\n",
    "                .build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Linear\n",
    "                .builder()\n",
    "                .setUnits(10)\n",
    "                .build());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We took a small liberty with the original model,\n",
    "removing the Gaussian activation in the final layer.\n",
    "Other than that, this network matches\n",
    "the original LeNet5 architecture. We also create the Model and \n",
    "Trainer object so that we initialize the structure once.\n",
    "\n",
    "By passing a single-channel (black and white)\n",
    "$28 \\times 28$ image through the net\n",
    "and printing the output shape at each layer,\n",
    "we can inspect the model to make sure \n",
    "that its operations line up with \n",
    "what we expect from :numref:`img_lenet_vert`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float lr = 0.9f;\n",
    "Model model = Model.newInstance(\"cnn\");\n",
    "model.setBlock(block);\n",
    "\n",
    "Loss loss = Loss.softmaxCrossEntropyLoss();\n",
    "\n",
    "Tracker lrt = Tracker.fixed(lr);\n",
    "Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build();\n",
    "\n",
    "DefaultTrainingConfig config = new DefaultTrainingConfig(loss).optOptimizer(sgd) // Optimizer (loss function)\n",
    "        .optDevices(Engine.getInstance().getDevices(1)) // Single GPU\n",
    "        .addEvaluator(new Accuracy()) // Model Accuracy\n",
    "        .addTrainingListeners(TrainingListener.Defaults.basic());\n",
    "\n",
    "Trainer trainer = model.newTrainer(config);\n",
    "\n",
    "NDArray X = manager.randomUniform(0f, 1.0f, new Shape(1, 1, 28, 28));\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "Shape currentShape = X.getShape();\n",
    "\n",
    "for (int i = 0; i < block.getChildren().size(); i++) {\n",
    "    Shape[] newShape = block.getChildren().get(i).getValue().getOutputShapes(new Shape[]{currentShape});\n",
    "    currentShape = newShape[0];\n",
    "    System.out.println(block.getChildren().get(i).getKey() + \" layer output : \" + currentShape);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the height and width of the representation\n",
    "at each layer throughout the convolutional block \n",
    "is reduced (compared to the previous layer).\n",
    "The first convolutional layer uses $2$ pixels of padding \n",
    "to compensate for the the reduction in height and width\n",
    "that would otherwise result from using a $5 \\times 5$ kernel.\n",
    "In contrast, the second convolutional layer foregoes padding, \n",
    "and thus the height and width are both reduced by $4$ pixels.\n",
    "As we go up the stack of layers,\n",
    "the number of channels increases layer-over-layer\n",
    "from 1 in the input to 6 after the first convolutional layer\n",
    "and 16 after the second layer.\n",
    "However, each pooling layer halves the height and width.\n",
    "Finally, each fully-connected layer reduces dimensionality,\n",
    "finally emitting an output whose dimension \n",
    "matches the number of classes.\n",
    "\n",
    "![Compressed notation for LeNet5](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/lenet-vert.svg)\n",
    "\n",
    ":label:`img_lenet_vert`\n",
    "\n",
    "\n",
    "## Data Acquisition and Training\n",
    "\n",
    "Now that we have implemented the model,\n",
    "let's run an experiment to see how LeNet fares on Fashion-MNIST."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 256;\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 10);\n",
    "double[] trainLoss;\n",
    "double[] testAccuracy;\n",
    "double[] epochCount;\n",
    "double[] trainAccuracy;\n",
    "\n",
    "epochCount = new double[numEpochs];\n",
    "\n",
    "for (int i = 0; i < epochCount.length; i++) {\n",
    "    epochCount[i] = (i + 1);\n",
    "}\n",
    "\n",
    "FashionMnist trainIter = FashionMnist.builder()\n",
    "        .optUsage(Dataset.Usage.TRAIN)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "\n",
    "FashionMnist testIter = FashionMnist.builder()\n",
    "        .optUsage(Dataset.Usage.TEST)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "                            \n",
    "trainIter.prepare();\n",
    "testIter.prepare();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While convolutional networks have few parameters,\n",
    "they can still be more expensive to compute\n",
    "than similarly deep multilayer perceptrons\n",
    "because each parameter participates in many more\n",
    "multiplications.\n",
    "If you have access to a GPU, this might be a good time\n",
    "to put it into action to speed up training."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The training function `trainingChapter6` is also similar \n",
    "to `trainChapter3` defined in :numref:`sec_softmax_scratch`. \n",
    "Since we will be implementing networks with many layers \n",
    "going forward, we will rely primarily on DJL.\n",
    "The following train function assumes a DJL model \n",
    "as input and is optimized accordingly. \n",
    "We initialize the model parameters \n",
    "on the block using the Xavier initializer.\n",
    "Just as with MLPs, our loss function is cross-entropy,\n",
    "and we minimize it via minibatch stochastic gradient descent. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public void trainingChapter6(ArrayDataset trainIter, ArrayDataset testIter,\n",
    "             int numEpochs, Trainer trainer) throws IOException, TranslateException {\n",
    "\n",
    "    double avgTrainTimePerEpoch = 0;\n",
    "    Map<String, double[]> evaluatorMetrics = new HashMap<>();\n",
    "\n",
    "    trainer.setMetrics(new Metrics());\n",
    "\n",
    "    EasyTrain.fit(trainer, numEpochs, trainIter, testIter);\n",
    "\n",
    "    Metrics metrics = trainer.getMetrics();\n",
    "\n",
    "    trainer.getEvaluators().stream()\n",
    "        .forEach(evaluator -> {\n",
    "            evaluatorMetrics.put(\"train_epoch_\" + evaluator.getName(), metrics.getMetric(\"train_epoch_\" + evaluator.getName()).stream()\n",
    "                    .mapToDouble(x -> x.getValue().doubleValue()).toArray());\n",
    "            evaluatorMetrics.put(\"validate_epoch_\" + evaluator.getName(), metrics.getMetric(\"validate_epoch_\" + evaluator.getName()).stream()\n",
    "                    .mapToDouble(x -> x.getValue().doubleValue()).toArray());\n",
    "        });\n",
    "\n",
    "    avgTrainTimePerEpoch = metrics.mean(\"epoch\");\n",
    "\n",
    "    trainLoss = evaluatorMetrics.get(\"train_epoch_SoftmaxCrossEntropyLoss\");\n",
    "    trainAccuracy = evaluatorMetrics.get(\"train_epoch_Accuracy\");\n",
    "    testAccuracy = evaluatorMetrics.get(\"validate_epoch_Accuracy\");\n",
    "\n",
    "    System.out.printf(\"loss %.3f,\" , trainLoss[numEpochs-1]);\n",
    "    System.out.printf(\" train acc %.3f,\" , trainAccuracy[numEpochs-1]);\n",
    "    System.out.printf(\" test acc %.3f\\n\" , testAccuracy[numEpochs-1]);\n",
    "    System.out.printf(\"%.1f examples/sec \\n\", trainIter.size() / (avgTrainTimePerEpoch / Math.pow(10, 9)));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let us train the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainingChapter6(trainIter, testIter, numEpochs, trainer);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Contour Gradient Descent.](https://d2l-java-resources.s3.amazonaws.com/img/chapter_convolution_neural_network_leNet.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"train loss\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"test acc\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "    DoubleColumn.create(\"epoch\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "    DoubleColumn.create(\"metrics\", ArrayUtils.addAll(trainLoss, ArrayUtils.addAll(trainAccuracy, testAccuracy))),\n",
    "    StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epoch\", \"metrics\", \"lossLabel\"), \"text/html\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "* A ConvNet is a network that employs convolutional layers.\n",
    "* In a ConvNet, we interleave convolutions, nonlinearities, and (often) pooling operations.\n",
    "* These convolutional blocks are typically arranged so that they gradually decrease the spatial resolution of the representations, while increasing the number of channels.\n",
    "* In traditional ConvNets, the representations encoded by the convolutional blocks are processed by one (or more) dense layers prior to emitting output.\n",
    "* LeNet was arguably the first successful deployment of such a network.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Replace the average pooling with max pooling. What happens?\n",
    "1. Try to construct a more complex network based on LeNet to improve its accuracy.\n",
    "    * Adjust the convolution window size.\n",
    "    * Adjust the number of output channels.\n",
    "    * Adjust the activation function (ReLU?).\n",
    "    * Adjust the number of convolution layers.\n",
    "    * Adjust the number of fully connected layers.\n",
    "    * Adjust the learning rates and other training details (initialization, epochs, etc.)\n",
    "1. Try out the improved network on the original MNIST dataset.\n",
    "1. Display the activations of the first and second layer of LeNet for different inputs (e.g., sweaters, coats)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
